﻿using DataProcessModule;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Helpers;
using System.Windows.Forms;

namespace testTcpServer
{
    public partial class FireBoxServer : Form
    {
        private static BytProcess _bp;
        //private byte[] ReceivedStream;
        private static byte[] header;
        private static byte[] tail;
        public Dictionary<string, NetWorkHelper.IModels.IClient> TerminalAddressAndDeviceID;
        public Dictionary<string, byte[]> BufferRestore;
  
        public FireBoxServer()
        {
            InitializeComponent();
            InitializeContent();
                    
        }
        private void btnExitProgram_Click(object sender, EventArgs e)
        {      
 
            iTcpServer1.Stop();            
            this.Close();
        }
        /// <summary>
        /// 初始化数据，启动服务
        /// </summary>
        public void InitializeContent()
        {
            //初始化变量
            TerminalAddressAndDeviceID = new Dictionary<string, NetWorkHelper.IModels.IClient>();
            BufferRestore = new Dictionary<string, byte[]>();
            this.textBoxReceivedMesage.Text = string.Empty;
            this.textBoxSendedMessage.Text = string.Empty;
            _bp = new BytProcess();
            header = new byte[] { 0x7e };
            tail = new byte[] { 0x7e };
            //读取端口，启动TCP服务1，TCP服务2配置已读取，根据需要启动            
            int num_1 = 0;
            int num_2 = 0;
            Int32.TryParse(ConfigrationSettingsReader.TcpServerPort_1, out num_1);
            Int32.TryParse(ConfigrationSettingsReader.TcpServerPort_2, out num_2);
            this.iTcpServer1.ServerPort = num_1;
            this.iTcpServer2.ServerPort = num_2;
            this.iTcpServer1.Start();
           
            //启动发送消息功能
            ServerSendData();  
        }

        #region tcpserver1
        /// <summary>
        /// tcp解析数据并存储服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>        
        public void ServerSendData()
        {
            System.Threading.ThreadPool.QueueUserWorkItem(t => {
                while (true)
                {
                    if (_bp.BytArr != null && TerminalAddressAndDeviceID != null)
                    {
                        for (int i = 0; i < _bp.BytArr.Count; ++i)
                        {
                            //string  _terminalk = _bp.GetDeviceTerminalkey(_bp.BytArr[i]);
                            try
                            {
                                NetWorkHelper.IModels.IClient _ic = new NetWorkHelper.IModels.IClient();
                                if (TerminalAddressAndDeviceID.TryGetValue(_bp.GetDeviceTerminalkey(_bp.BytArr[i]), out _ic) == false) continue;
                                //this.iTcpServer1.SendData(TerminalAddressAndDeviceID[_bp.GetDeviceTerminalkey(_bp.BytArr[i])], _bp.BytArr[i]);
                                this.iTcpServer1.SendData(_ic, _bp.BytArr[i]);
                                if (this.textBoxSendedMessage.TextLength > 2800) this.textBoxSendedMessage.Text = string.Empty;
                                this.textBoxSendedMessage.Text += BC.ToBCDString(_bp.BytArr[i]) + Environment.NewLine;

                                lock (_bp.BytArLock)
                                {
                                    _bp.BytArr.RemoveAt(i);
                                }
                            }
                            catch (Exception e)
                            {
                            }                          
                        }
                        System.Threading.Thread.Sleep(1000);
                    }
                }
            });
        }
        private void iTcpServer1_OnErrorMsg(object sender, NetWorkHelper.ICommond.TcpServerErrorEventArgs e)
        {

        }

        private void iTcpServer1_OnGetLog(object sender, NetWorkHelper.ICommond.TcpServerLogEventArgs e)
        {

        }

        private void iTcpServer1_OnOfflineClient(object sender, NetWorkHelper.ICommond.TcpServerClientEventArgs e)
        {

        }

        private void iTcpServer1_OnOnlineClient(object sender, NetWorkHelper.ICommond.TcpServerClientEventArgs e)
        {

        }

        private void iTcpServer1_OnRecevice(object sender, NetWorkHelper.ICommond.TcpServerReceviceaEventArgs e)
        {
            string termkey = _bp.GetDeviceTerminalkey(e.Data);
            TerminalAddressAndDeviceID[termkey] = e.IClient;
            byte[] temp = new byte[1];
            if (BufferRestore.TryGetValue(termkey, out temp) == false)
            {
                BufferRestore[termkey] = e.Data;
            }
            else if (BufferRestore[termkey].Length == 0)
            {
                BufferRestore[termkey] = e.Data;               
            }
            else 
            {
                BufferRestore[termkey].Concat(e.Data);
            }
            if (this.textBoxReceivedMesage.TextLength > 1024) this.textBoxReceivedMesage.Text = string.Empty;
            this.textBoxReceivedMesage.Text += BC.ToBCDString(e.Data) + Environment.NewLine;
            while (BufferRestore[termkey].Length >= 12)
            {
                int _start, _end = -1;
                _start = BC.FindSymbol(BufferRestore[termkey], header);
                if ((_start != -1) && ((_start + 3) <= BufferRestore[termkey].Length))
                {
                    _end = BC.FindSymbol(BufferRestore[termkey], tail, _start + 1);
                }
                if (_start == -1 || _end == -1 ) break;

                byte[] destinationArray = new byte[_end - _start + 1];
                Array.Copy(BufferRestore[termkey], _start, destinationArray, 0, destinationArray.Length);
                BufferRestore[termkey] = BufferRestore[termkey].Skip(_end + 1).ToArray();

                _bp.ByteDigitsForge(destinationArray);               
            }
        }

        private void iTcpServer1_OnReturnClientCount(object sender, NetWorkHelper.ICommond.TcpServerReturnClientCountEventArgs e)
        {
            //BytProcess bytProcess = new BytProcess(e.Data);
        }

        private void iTcpServer1_OnSendDateSuccess(object sender, NetWorkHelper.ICommond.TcpServerSendReturnEventArgs e)
        {

        }

        private void iTcpServer1_OnStateInfo(object sender, NetWorkHelper.ICommond.TcpServerStateEventArgs e)
        {

        }
        #endregion
        #region tcpserver2
        /// <summary>
        /// tcp回发终端服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>       
        private void iTcpServer2_OnRecevice(object sender, NetWorkHelper.ICommond.TcpServerReceviceaEventArgs e)
        {
            
        }

        private void iTcpServer2_OnErrorMsg(object sender, NetWorkHelper.ICommond.TcpServerErrorEventArgs e)
        {
            throw new System.NotImplementedException();
        }

        private void iTcpServer2_OnReturnClientCount(object sender, NetWorkHelper.ICommond.TcpServerReturnClientCountEventArgs e)
        {
            //throw new System.NotImplementedException();
        }

        private void iTcpServer2_OnStateInfo(object sender, NetWorkHelper.ICommond.TcpServerStateEventArgs e)
        {
            //throw new System.NotImplementedException();
        }

        private void iTcpServer2_OnOnlineClient(object sender, NetWorkHelper.ICommond.TcpServerClientEventArgs e)
        {
            //throw new System.NotImplementedException();
        }

        private void iTcpServer2_OnOfflineClient(object sender, NetWorkHelper.ICommond.TcpServerClientEventArgs e)
        {
            //throw new System.NotImplementedException();
        }

        private void iTcpServer2_OnGetLog(object sender, NetWorkHelper.ICommond.TcpServerLogEventArgs e)
        {
            //throw new System.NotImplementedException();
        }

        private void iTcpServer2_OnSendDateSuccess(object sender, NetWorkHelper.ICommond.TcpServerSendReturnEventArgs e)
        {
            //throw new System.NotImplementedException();
        }

        #endregion

        #region button function area
        private void buttonTestinUpgrade_Click(object sender, EventArgs e)
        {
            //_bp.ServerActionsHandle(ServerAction.UpgradeFirebox);
        }

        private void btnStartServer_Click(object sender, EventArgs e)
        {
            this.iTcpServer1.Start();
        }

        private void btnStopServer_Click(object sender, EventArgs e)
        {
            this.iTcpServer1.Stop();
        }
        #endregion
    }
}
